package com.yitianyigexiangfa.coap.cbor.cborjava;

import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.DataItem;
import com.yitianyigexiangfa.coap.cbor.util.ConvertUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * @author Bill Lau
 * @date 2017-12-22
 */
public class CborJavaDemo {

    public static void main(String[] args) throws CborException {
        // ================== 编码 ==================
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        new CborEncoder(baos).encode(new CborBuilder()
                                             .add(23)
                                             .add(24)
                                             .add(-1)
                                             .add(-24)
                                             .add(1.2)
                                             .add(2e13)
                                             .add("HI")
                                             .addArray()
                                             .add(25)
                                             .end()
                                             .build()
        );
        byte[] encodedBytes = baos.toByteArray();
        String result = ConvertUtil.bytesToHex(encodedBytes);
        System.out.println(result);

        // ================== 解码 ==================
        ByteArrayInputStream bais = new ByteArrayInputStream(encodedBytes);
        List<DataItem> dataItemList = new CborDecoder(bais).decode();
        for (DataItem item : dataItemList) {
            System.out.println(item.toString());
        }
    }

}
